qui(
    function(require, exports, module) {


        PreSet.Grid = function(options) {
            this.dao = PreSet.Dao;
            this.config = PreSet.Config;
            this.options = options || {};
			this.channel_id = Com.url.getQueryValue("channel_id",location.href);
			this.channel_name = Com.url.getQueryValue("channel_name",location.href);
            this.construct = options.construct || function() {
                this.init();
            };
            this.construct.call(this);

        };

        Com.inherits(PreSet.Grid, Ancestor.Grid).extend({
            init: function() {
                var self = this;
                var $container = self.options.$container;
                self.$grid = $container.find('table.grid');
                self.perpareData();
                self.bindBasicEvent();
                self.initSuggest();
            },
            perpareData: function() {
                //var request = {};
                //request.url=PreSet.Constant.ipListUrl;
                //request.type='get';
                //request.params = {'type':0,'area':0,'from_client':'true'};
                //request.needCookie = {};
                //var requestJson = JSON.stringify(request);

                //this.dao.redirect({request:request}, function(data){
                //    $('#ipList').attr("ipList") = data;
                //});
                this.dao.ipList({'type':0,'area':0,'from_client':'true'}, function(data){
                    $('#ipList').attr("ipList", JSON.stringify(data));
                });
                //$("#env").attr("env") = PreSet.Constant.preRecocordUrl;
            },

            bindBasicEvent: function() {
                var self = this;
                var $container = self.options.$container;
                var $form = $container.find('form[name="basicFrm"]');
                self.bindFormEvent($form);
                $container.find('.query-btn').on('click.query', function() {
                    self.query();
                    return false;
                });

                $form.find('.query-add').click(function() {
					window.open("/epg/live2VOD_preset_edit.html?modify=add&channel_id="+self.channel_id+"&channel_name="+self.channel_name);
                });

				var regionList = ['cq','sh','bj'];

                $form.find('.pre-input').click(function() {
					var ipObj = JSON.parse($('#ipList').attr("ipList")),
						options = '';

					if(ipObj.code==200)
					{
						$.each(ipObj.response.list,function(i,v){
							options +='<option value="'+v[0]+'" >'+v[0]+'['+regionList[v[1]]+']</option>';
						});
					}

					var html = '<div style="text-align:center;"><h3 style="margin-left:-170px;">请选择导入的频道信息</h3><div class="row">服务器ip:<select id="dst_ip">'
					+options+'</select></div><div class="row">频道代号:<input type="text" name="channel_code"/></div><div  class="controls"><button type="button" class="btn btn-primary pre_confirm">确定</button>&nbsp;<button type="submit"  class="btn btn-primary pre_cancel">取消</button></div></div>';
					$(html).dialog({
						/* title : title,*/
						width: 300,
						height: 200,
						modal: true,
						appendTo: $container,
						close: function() {
						}
					});

					$(".pre_cancel").unbind("click").bind("click",function(){
						$(".ui-dialog-titlebar-close").trigger("click");
					});

					$(".pre_confirm").unbind("click").bind("click",function(){

						self.dao.saveAssociation({'channel_id':self.channel_id,'dst_channel_ip':$("#dst_ip").val(),'dst_channel_code':$('[name="channel_code"]').val()}, function(data){
							if(data.response.status === 0)
							{
								$(document).tips({
									content: "关联成功",
									type: "success"
								});

								setTimeout("window.location.reload()",1000);
								$(".ui-dialog-titlebar-close").trigger("click");
							}
							else
							{
								$(document).tips({
									content: data.response.error,
									type: "error"
								});
							}

						});
					});

                });

				$container.find('input[name="thriftVideo.albumId"]').blur(function(){
					if($(this).val()==="")
					{
						$container.find('input[name="ablum_id"]').val("");
						$container.find('input[name="ablum_name"]').val("");
					}
				});

				$("[type=reset]").click(function(){
					$container.find('input[name="ablum_id"]').val("");
					$container.find('input[name="ablum_name"]').val("");
				});

			},

			bindFormEvent: function($form) {
                var self = this;
                $form.find('input[name="start_time"]').timepicker({
                    onClose: function(selectedDate) {
                        $form.find('input[name="start_time"]').timepicker("option", selectedDate);
                    },
                    timeFormat: 'HH:mm:ss'
                });
                $form.find('input[name="stop_time"]').timepicker({
                    onClose: function(selectedDate) {
                        $form.find('input[name="stop_time"]').timepicker("option", selectedDate);
                    },
                    timeFormat: 'HH:mm:ss'
                });
                //Suggest.Action.channel($form.find('input[name=channeltype]'), {
                //    isFgtw: User.Util.isPartner() ? true : false
                //});

			},

            run: function(options, callback) {
                var self = this;
                var gridConfig = self.getGridConfig();

                self.echoQuery();

                options = $.extend(true, {
                    width: 1700,
                   // multiselect: true,
                    multiselectWidth: 30,
                    shrinkToFit: false,
                    // idPrefix: 'Video-',
                    autowidth: false
                }, gridConfig, options);
                self.initGrid.call(this, options, callback);
                self.loadTableByDate();
            },

            getParam: function() {
                var self = this;
                var $container = self.options.$container;

                var $grid = self.$grid;
                var params = {"channel_id":self.channel_id};
                var $form = $container.find('form[name="basicFrm"]');

                var $elements = $.makeArray($form.prop('elements')).filter(function(item) {
					if($(item).attr("name") != "thriftVideo.albumId")
					{
						return true;
					}
					return false;
                });

				var checkboxVal = [];
                var name;
                var key;
                $.each($elements, function() {
                    name = this.name;
                    if (name) {
						if(name=='repeat_info')
						{   /*
							if(params[name]==undefined)
							{
								params[name] = [];
							}
							*/
							if(this.checked)
							{
								checkboxVal.push($(this).val());
							}
						}
						else if(name=="scale")
						{
							if(this.checked)
							{
								params[name] = $(this).val();
							}
						}
						else
						{
							if($(this).val()){
								params[name] = $(this).val();
							}
						}
                    }

                });
				if(checkboxVal.length!==0){
					params['repeat_info']=JSON.stringify(checkboxVal);//params['repeat_info'].join(',');
				}
                return params;
            },
            loadTableByDate:function(){
                var self = this;
                self.$grid.setGridParam({page: 1, url:'/api/redirect' , loadtext: '加载中...',
                    datatype:"json",
                    loadui: "block",
                    postData:{"request": JSON.stringify({url: "http://lego.iqiyi.com/live2VOD/preSet/get", type: "get", params:{channel_id: self.channel_id} , needCookie: false})}
                    }).trigger("reloadGrid");
            },

            query: function() {
                var self = this;
                var $container = self.options.$container;
                var $grid = self.$grid;
                self.overridePostData($grid);
                var params = self.getParam();
                $grid.jqGrid('setGridParam', {
                    page: 1,
                    datatype: "json",
                    postData: {"request": JSON.stringify({url: "http://lego.iqiyi.com/live2VOD/preSet/get", type: "get", params:params , needCookie: false})}
                }).trigger('reloadGrid');
            },
            initSuggest:function(){
                var self = this;
                var $container = self.options.$container;
                var type = 'properTitle';
                var tpl = '<div><div class="contract-item">{{html varCatalogStatusColor }}' +
                                    '<span class="contract-width100">${entityId}</span>' +
                                    '<span class="contract-width150">{{html displayName }}</span>' +
                                    '<span class="contract-width150">{{html properTitle }}</span>' +
                                    '<span class="contract-width80" >${channelName}</span>' +
                                    '<span class="contract-width80" >${categoryName}</span>' +
                                    '<span class="contract-width50">${totalNumberOfEpisodes}</span>' +
                                    '<span class="contract-width100">${globalPublishDate}</span>' +
                                    '</div></div>';
                var title = {
                                entityId: '专辑ID',
                                qipuId: '奇谱ID',
                                displayName: '专辑显示名(无多发)',
                                properTitle: '专辑原名(无多发)',
                                channelName: '所属频道',
                                categoryName: '主频道',
                                totalNumberOfEpisodes: '总集数',
                                globalPublishDate: '发行时间'
                            };
                var getHtmlByData = function(data) {
                                    var htmls = [];
                                    var htmlStr = $('<div></div>').html($(tpl).tmpl(data));
                                    return htmlStr.html();
                                };
                var titleHtml = getHtmlByData(title);
                var albumIdSuggest = {
                    options:{
                        source:"/api/redirect",
                        header: titleHtml,
                        method: "post",
                        multiple: false,
                        select: function(event, ui) {

                            if (ui && ui.item) {
                                $container.find('input[name="thriftVideo.albumId"]').attr('data-displayName', ui.item.properTitle);
                                $container.find('input[name="thriftVideo.albumId"]').attr('data-channel-id', ui.item.channel);
                                $container.find('input[name="ablum_id"]').val(ui.item.id);
                                $container.find('input[name="ablum_name"]').val(ui.item.properTitle.replace(/<b>|<\/b>/g,""));
                            }
                        },
                        parseValue: function() {
                            var val = this.element.val();
                            var ret = [];
                            if (val) {
                                var items = val.split(';');
                                $.each(items, function(i, item) {
                                    item = item.split(',');
                                    ret.push({
                                        value: item[1],
                                        id: item[0],
                                        label: item[1]
                                    });
                                });
                            }
                            this._value('');
                            return ret;
                        },
                        getParam: function (term) {
                            var params = term.length == 0 ? {type:"properTitle", filter_EQI_isMainChannel:1}:{type:"properTitle", filter_EQI_isMainChannel:1, word: term};
                            var requestData = {url:  "http://lego.iqiyi.com/suggest/album", type: "get", params:params , needCookie: false};
                            return {"request": JSON.stringify(requestData), timeSign: new Date().getTime()}
                        },

                        process: function(json) {
                            var data = json.data;
                            if (!data) {
                                return [];
                            }
                            var ret = [];
                            $.map(data, function(item) {
                                ret.push($.extend(true, {
                                    value: item[type]
                                }, item, {
                                    // displayName: item[type],
                                    id: item.entityId
                                }));
                            });
                            return ret;
                        },

                        template: function (item) {
                            return getHtmlByData(item);
                        }
                    }
                };
                $("input[name='thriftVideo.albumId']").suggest(albumIdSuggest.options);
            },
			del : function(channel_id,ablum_id){
                var self = this;

                if(window.confirm('是否确认删除该专辑信息？')){
                    var request = {};
                    request.url='http://lego.iqiyi.com/live2VOD/preSet/del';
                    request.type='get';
                    request.params = {'channel_id':channel_id,'ablum_id':ablum_id};
                    request.needCookie = {};
                    var requestJson = JSON.stringify(request);

                    this.dao.redirect({request:JSON.stringify(request)}, function(){self.query();});
                    return true;
                }
            }


        });

    }
);